package com.bnlr.lrparking.appui.publish;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiNearbySearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;

/**
 * 选取停车场位置
 */
public class SelectParkingActivity extends BaseActivity {
    private TextureMapView mMapView;
    private BaiduMap baiduMap;
    private ImageView ivOrigin;
    private TextView tvName;
    private EditText etAddress;
    private LocationClient mLocationClient = null;
    private LocationListener mLocationListener = null;
    private GeoCoder mSearch;
    private LatLng centerLatlng;
    private LatLng initLatlng;
    private TextView sure;
    InfoWindow mInfoWindow;
    private Button windowButton;
    private String selectCity;
    private boolean onActivityResult = false;
    private TextView title;
    private PoiSearch poiSearch;
    private String cityName = "",areaName = "",provinceName ="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_parking);
        title = (TextView) findViewById(R.id.tv_nav_title);
        mMapView = (TextureMapView) findViewById(R.id.mapView);
        tvName = (TextView) findViewById(R.id.tv_name);
        etAddress = (EditText) findViewById(R.id.et_detail_address);
        ivOrigin = (ImageView) findViewById(R.id.iv_my_location);
        sure = (TextView) findViewById(R.id.sure);
        sure.setEnabled(false);
        title.setText("确认车位地址");
        windowButton = new Button(getApplicationContext());
        windowButton.setBackgroundResource(R.drawable.popup);
        windowButton.setText("车位在这里");
        windowButton.setTextColor(Color.WHITE);
        baiduMap = mMapView.getMap();
        mMapView.showScaleControl(false);
        mMapView.showZoomControls(false);
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(new MyGetGeoCoderResultListener());
        poiSearch = PoiSearch.newInstance();
        poiSearch.setOnGetPoiSearchResultListener(poiListener);
        LatLng cen = new LatLng(34.751778,113.667639);
        MapStatus mapStatus = new MapStatus.Builder().target(cen).zoom(18).build();
        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus));
        /*baiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(mapStatus));
        baiduMap.setMyLocationConfiguration(new MyLocationConfiguration(
                MyLocationConfiguration.LocationMode.FOLLOWING, true, null));*/
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        mLocationClient = new LocationClient(this,getLocationOption());
        mLocationListener = new LocationListener();
        mLocationClient.registerLocationListener(mLocationListener);
        mLocationClient.start();

        baiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            /**
             * 手势操作地图，设置地图状态等操作导致地图状态开始改变。
             * @param status
             * 地图状态改变开始时的地图状态
             */
            @Override
            public void onMapStatusChangeStart(MapStatus status) {
                sure.setEnabled(false);
                baiduMap.hideInfoWindow();

            }
            /**
             * 地图状态改变结束
             * @param status
             * 地图状态改变结束后的地图状态
             */
            @Override
            public void onMapStatusChangeFinish(MapStatus status) {
                sure.setEnabled(true);
                if (onActivityResult) {
                    //创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
                    mInfoWindow = new InfoWindow(windowButton, centerLatlng, -50);
                    //显示InfoWindow
                    baiduMap.showInfoWindow(mInfoWindow);
                    onActivityResult = false;
                } else {
                    centerLatlng = status.target;
                    poiSearch.searchNearby(new PoiNearbySearchOption()
                            .location(centerLatlng)
                            .pageCapacity(7)
                            .radius(500)
                            .keyword("停车"));

                }
            }
            /**
             * 地图状态变化中
             * @param status
             */
            @Override
            public void onMapStatusChange(MapStatus status) {

            }
        });
        ivOrigin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(initLatlng);
                baiduMap.animateMapStatus(u);
            }
        });
        tvName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(tvName.getText().toString())) {
                    PoiInfo poiInfo = new PoiInfo();
                    poiInfo.city = selectCity;
                    poiInfo.name = tvName.getText().toString();
                    poiInfo.address = etAddress.getText().toString();
                    poiInfo.location = centerLatlng;
                    startActivityForResult(new Intent(SelectParkingActivity.this, MapSearchActivity.class)
                            .putExtra("current_info", poiInfo), 1000);
                }
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (centerLatlng != null) {
                    Intent intent = new Intent();
                    intent.putExtra("location",centerLatlng);
                    intent.putExtra("address",etAddress.getText().toString());
                    intent.putExtra("cityName",cityName);
                    intent.putExtra("areaName",areaName);
                    intent.putExtra("areaName",areaName);
                    intent.putExtra("provinceName",provinceName);
                    setResult(1008,intent);
                    finish();
                } else {
                    ToastUtils.showShort("未获取到位置");
                }
            }
        });
    }

    class MyGetGeoCoderResultListener implements OnGetGeoCoderResultListener {

        @Override
        public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            if (reverseGeoCodeResult != null && reverseGeoCodeResult.getAddressDetail() != null) {
                cityName = reverseGeoCodeResult.getAddressDetail().city;
                areaName = reverseGeoCodeResult.getAddressDetail().district;
                provinceName = reverseGeoCodeResult.getAddressDetail().province;
            }
        }
    }
    OnGetPoiSearchResultListener poiListener = new OnGetPoiSearchResultListener(){

        @Override
        public void onGetPoiResult(PoiResult result){
            //获取POI检索结果
            if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
                return;
            }

            PoiInfo poiInfo = result.getAllPoi().get(0);
            selectCity = poiInfo.city;
            tvName.setText(poiInfo.name);
            etAddress.setText(poiInfo.address);
            etAddress.setSelection(etAddress.getText().length());
            //创建InfoWindow , 传入 view， 地理坐标， y 轴偏移量
            mInfoWindow = new InfoWindow(windowButton, centerLatlng, -50);
            //显示InfoWindow
            baiduMap.showInfoWindow(mInfoWindow);
//            LogUtils.e("需要的",poiInfo.location);
            mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(poiInfo.location));
        }
        @Override
        public void onGetPoiDetailResult(PoiDetailResult result){
            //获取Place详情页检索结果
        }
        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

        }
    };
    /**
     * 定位回调
     */
    private class LocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            //  定位监听
            if (bdLocation == null) {
                return;
            }
            sure.setEnabled(true);
            LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll); //定位点移至中心
            baiduMap.animateMapStatus(u);
            initLatlng = ll;
            selectCity = bdLocation.getCity();
            BitmapDescriptor bitmap = BitmapDescriptorFactory
                    .fromResource(R.drawable.current_location);
            OverlayOptions option = new MarkerOptions()
                    .position(ll)
                    .icon(bitmap);
            baiduMap.addOverlay(option);
            centerLatlng = ll;
            tvName.setText(bdLocation.getAddrStr());
            etAddress.setText(bdLocation.getAddrStr() + bdLocation.getDistrict());
            etAddress.setSelection(etAddress.getText().length());
        }
    }

    private LocationClientOption getLocationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setScanSpan(0);
        option.setAddrType("all");
        option.setIsNeedAddress(true);
        return option;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1000 && resultCode == 1005) {
            onActivityResult = true;
            PoiInfo info = data.getParcelableExtra("back_info");
            selectCity = info.city;
            centerLatlng = info.location;
           // mSearch.geocode(new GeoCodeOption().city(info.city).address(info.address));
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(info.location); //定位点移至中心
            baiduMap.animateMapStatus(u);
            tvName.setText(info.name);
            etAddress.setText(info.address);
            etAddress.setSelection(etAddress.getText().length());
            mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(info.location));

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        mLocationClient.unRegisterLocationListener(mLocationListener);
        mLocationClient.stop();
        mSearch.destroy();
        poiSearch.destroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }
}
